﻿using COSXML.Model.Tag;
using Db;
using Db.Models;
using Db.Models.Base;
using Db.Repos;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using TecentCOS.Configs;
using TecentCOS.Models;
using static Db.Enums.BlindWaterMark;

namespace TecentCOS.webapi.Controllers
{
    public class WaterMarkController : BaseController
    {
        Bll bll = new Bll();

        [HttpGet]
        public ResponseModel GetBuckets()
        {
            var res = TecentCosService.Instance().GetBuckets();

            return base.Success(res);
        }


        /// <summary>
        /// 读取所有bucket
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetListFromBucket()
        {
            var res = TecentCosService.Instance().GetListFromBucket("");
            return base.Success(res);
        }

        [HttpGet]
        public string GetPreviewUrl(string key)
        {
          return   TecentCosService.Instance().GeneratePreviewUrl(key);
        }

        /// <summary>
        /// 读取图片列表
        /// </summary>
        /// <param name="marker"></param>
        /// <param name="type"></param>
        /// <param name="watermarktype"></param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetImagesFromBucket(string marker = "", int type = 0, int watermarktype = 1)
        {
            string prefix = "";
            string[] prefixes = { DirectoryNames.Origin, DirectoryNames.WaterMarkMaterial, DirectoryNames.Processed };
            prefix = prefixes[type];

            var res = TecentCosService.Instance().GetListFromBucket(marker, prefix, "9");
            var contentList = res.contentsList;
            List<UploadModelBase> uploadModels = new List<UploadModelBase>();
            switch (type)
            {
                case 0:
                    {
                        contentList.ForEach((content) =>
                        {

                            string filename = content.key.Substring(content.key.LastIndexOf("/") + 1);
                            var findOne = Repos.OriginImageDb.GetSingle(img => filename == img.ImageName + "." + img.Extension);
                            if (findOne != null)
                            {
                                findOne.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(content.key);
                                uploadModels.Add(findOne);
                            }

                        });
                        break;
                    }

                case 1:
                    {
                        contentList.ForEach((content) =>
                        {

                            string filename = content.key.Substring(content.key.LastIndexOf("/") + 1);
                            var findOne = Repos.WaterMarkMaterialDb.GetSingle(img => filename == img.ImageName + "." + img.Extension);
                            if (findOne != null)
                            {
                                findOne.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(content.key);
                                uploadModels.Add(findOne);
                            }


                        });
                        break;
                    }
                case 2:
                    {
                        List<ProcessedImage> processedImages = new List<ProcessedImage>();

                        contentList.ForEach((content) =>
                        {


                            string filename = content.key.Substring(content.key.LastIndexOf("/") + 1);
                            var findOne = Repos.ProcessedImageDb.GetSingle(img => filename == img.ImageName + "." + img.Extension && watermarktype == (int)img.waterMarkType);
                            if (findOne != null)
                            {
                                findOne.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(content.key);
                                findOne.originImage = Repos.OriginImageDb.GetById(findOne.OriginImageId);
                                findOne.originImage.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(findOne.originImage.ObjectKey);
                                if (watermarktype != 3)
                                {
                                    findOne.waterMarkMaterial = Repos.WaterMarkMaterialDb.GetById(findOne.WaterMarkMaterialId);
                                    findOne.waterMarkMaterial.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(findOne.waterMarkMaterial.ObjectKey);

                                }

                                processedImages.Add(findOne);
                            }


                        });

                        return base.Success(new
                        {
                            marker = res.nextMarker,
                            list = processedImages
                        });

                        break;
                    }
            }
            object response = new
            {
                marker = res.nextMarker,
                list = uploadModels
            };



            return base.Success(response);

        }

        /// <summary>
        /// 上传时添加
        /// </summary>
        /// <param name="waterMark"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel AddWhenUpload(AddWaterMark waterMark)
        {

            Guid newWaterMarkId = Guid.Empty;
            Guid newOriginImgId = Guid.Empty;

            switch (waterMark.waterMarkType)
            {
                //原图只能使用未上传的  
                case WaterMarkType.HalfBlind:
                case WaterMarkType.FullBlind:
                    {
                        //未上传 -> 先上传水印
                        if (waterMark.watermarkImg.uploadStatus == UploadStatus.toupload) //
                        {
                            var watermarkRes = TecentCosService.Instance().PutObject(DirectoryNames.WaterMarkMaterial + waterMark.watermarkImg.ObjectKey,
                                 Convert.FromBase64String(waterMark.watermarkImg.FileData));
                            if (watermarkRes.httpCode == 200)
                            {
                                waterMark.watermarkImg.ObjectKey = "/" + DirectoryNames.WaterMarkMaterial + waterMark.watermarkImg.ObjectKey;
                                waterMark.watermarkImg.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(waterMark.watermarkImg.ObjectKey);
                                //上传水印图
                                var waterMarkInfo = TecentCosService.Instance().GetImageInfo(waterMark.watermarkImg.ObjectKey);
                                WaterMarkMaterial waterMarkMaterial = waterMark.watermarkImg.ConvertToUploadModel<WaterMarkMaterial>(waterMarkInfo);
                                newWaterMarkId = waterMarkMaterial.Id;
                                Repos.WaterMarkMaterialDb.Insert(waterMarkMaterial);

                            }
                            else
                            {
                                return Fail(watermarkRes, "水印图上传失败..");
                            }

                        }
                        else
                        {
                            var markMaterial = bll.FindUploadModel<WaterMarkMaterial>(Repos.WaterMarkMaterialDb, waterMark.watermarkImg.ObjectKey);

                            if (markMaterial == null)
                            {
                                waterMark.watermarkImg.ObjectKey = "/" + waterMark.watermarkImg.ObjectKey;
                                waterMark.watermarkImg.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(waterMark.watermarkImg.ObjectKey);
                                var waterMarkInfo = TecentCosService.Instance().GetImageInfo(waterMark.watermarkImg.ObjectKey);
                                WaterMarkMaterial waterMarkMaterial = waterMark.watermarkImg.ConvertToUploadModel<WaterMarkMaterial>(waterMarkInfo);
                                Repos.WaterMarkMaterialDb.Insert(waterMarkMaterial);

                            }
                            newWaterMarkId = markMaterial.Id;

                        }
                        break;
                    }

                //不需要上传水印图片
                case WaterMarkType.TextBlind:
                    {
                        break;
                    }
            }
            var res = TecentCosService.Instance().AddWaterMarkWhenUpload(waterMark);
            if (!res.Success)
            {
                return Fail(res);
            }

            var originImage = bll.FindUploadModel<OriginImage>(Repos.OriginImageDb, waterMark.originImg.ObjectKey);
            // 原图 db
            if (waterMark.originImg.uploadStatus == UploadStatus.toupload && originImage == null)
            {
                var imageInfo = TecentCosService.Instance().GetImageInfo("/" + DirectoryNames.Origin + waterMark.originImg.ObjectKey);
                waterMark.originImg.ObjectKey = "/" + DirectoryNames.Origin + waterMark.originImg.ObjectKey;
                originImage = waterMark.originImg.ConvertToUploadModel<OriginImage>(imageInfo);
                Repos.OriginImageDb.Insert(originImage);
            }

            newOriginImgId = originImage.Id;




            //处理结果 db
            var processedKey = res.ProcessResult.finalKey;

            ProcessedImage processedImage = bll.FindUploadModel<ProcessedImage>(Repos.ProcessedImageDb, processedKey);

            bool newProcess = false;
            newProcess = processedImage == null;

            ImageModel processedImg = (ImageModel)waterMark.originImg.Clone();

            processedImg.ObjectKey = processedKey;

            ImageInfoBase processedInfo = TecentCosService.Instance().GetImageInfo(processedKey.ToString());

            processedImage = processedImg.ConvertToUploadModel<ProcessedImage>(processedInfo);

            processedImage.OriginImageId = newOriginImgId;

            processedImage.Prefix = "type" + ((int)processedImage.waterMarkType).ToString() + "_";

            processedImage.waterMarkType = waterMark.waterMarkType;

            if (waterMark.waterMarkType == WaterMarkType.TextBlind)
            {
                processedImage.waterMarkText = waterMark.watermarktext;
                processedImage.WaterMarkMaterialId = Guid.Empty;
            }
            else if (waterMark.waterMarkType == WaterMarkType.HalfBlind || waterMark.waterMarkType == WaterMarkType.FullBlind)
            {
                processedImage.WaterMarkMaterialId = newWaterMarkId;
            }

            if (newProcess)
            {
                Repos.ProcessedImageDb.Insert(processedImage);
            }

            else
            {
                Repos.ProcessedImageDb.Update(processedImage);
            }


            return Success(res);

            //上传原图 
        }

        /// <summary>
        /// 下载时添加
        /// </summary>
        /// <param name="waterMark"></param>
        /// <returns></returns>
        [HttpPost]
        public FileStreamResult AddWhenDownLoad(AddWaterMark waterMark)
        {

            //WaterMark waterMark = JsonConvert.DeserializeObject<WaterMark>(model);
            switch (waterMark.waterMarkType)
            {
                //原图只能使用未上传的  
                case WaterMarkType.HalfBlind:
                case WaterMarkType.FullBlind:
                    {
                        //未上传 -> 先上传水印
                        if (waterMark.watermarkImg.uploadStatus == UploadStatus.toupload) //
                        {
                            var watermarkRes = TecentCosService.Instance().PutObject("watermark/" + waterMark.watermarkImg.ObjectKey,
                                 Convert.FromBase64String(waterMark.watermarkImg.FileData));
                            if (watermarkRes.httpCode == 200)
                            {
                                waterMark.watermarkImg.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(waterMark.watermarkImg.ObjectKey);
                            }
                            else
                            {
                                throw new Exception("水印图上传失败...");
                            }

                        }

                        else
                        {
                            //取在线Url

                        }
                        break;
                    }

                //不需要上传水印图片
                case WaterMarkType.TextBlind:
                    {
                        break;
                    }
            }
            var stream = TecentCosService.Instance().AddWaterMarkWhenDownLoad(waterMark);
            string realFileName = waterMark.originImg.ObjectKey;
            if (realFileName.Contains("/"))
            {
                realFileName = realFileName.Substring(realFileName.LastIndexOf("/") + 1);
            }


            var fileResult = new FileStreamResult(stream, "image/jpg", realFileName);

            return fileResult;


        }

        /// <summary>
        /// 提取
        /// </summary>
        /// <param name="waterMark"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel ExtractMark(AddWaterMark waterMark)
        {
            ResponseObject responseObj = new ResponseObject();
            switch (waterMark.extractType)
            {
                case ExtractType.ExtractNew:
                    {
                        if (waterMark.waterMarkType == WaterMarkType.HalfBlind && waterMark.originImg.uploadStatus == UploadStatus.toupload)
                        {
                            //先上传原图

                            var originRes = TecentCosService.Instance().PutObject(DirectoryNames.Extract + DirectoryNames.Origin + waterMark.originImg.ObjectKey,
                              Convert.FromBase64String(waterMark.originImg.FileData));
                            if (originRes.httpCode == 200)
                            {
                                //生成Url
                                waterMark.originImg.ObjectKey = "/" + DirectoryNames.Extract + DirectoryNames.Origin + waterMark.originImg.ObjectKey;
                                waterMark.originImg.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(waterMark.originImg.ObjectKey);
                                //写db
                            }
                        }
                        else if (waterMark.waterMarkType == WaterMarkType.FullBlind && waterMark.watermarkImg.uploadStatus == UploadStatus.toupload)
                        {
                            //先上传水印图
                            var watermarkRes = TecentCosService.Instance().PutObject(DirectoryNames.Extract + DirectoryNames.WaterMarkMaterial + waterMark.watermarkImg.ObjectKey,
                          Convert.FromBase64String(waterMark.watermarkImg.FileData));

                            if (watermarkRes.httpCode == 200)
                            {
                                //生成Url
                                waterMark.watermarkImg.ObjectKey = "/" + DirectoryNames.Extract + DirectoryNames.WaterMarkMaterial + waterMark.watermarkImg.ObjectKey;
                                waterMark.watermarkImg.PreviewUrl = TecentCosService.Instance().GeneratePreviewUrl(waterMark.watermarkImg.ObjectKey);
                                //写db
                            }

                        }
                        responseObj = TecentCosService.Instance().ExtractFromUpload(waterMark);

                        break;
                    }
                case ExtractType.ExtractExisted:
                    {
                        responseObj = TecentCosService.Instance().ExtractFromCloud(waterMark);
                        break;
                    }
            }

            if (responseObj.Success)
            {
                return Success(responseObj);
            }
            else
            {
                return Fail(responseObj);
            }
        }

        /// <summary>
        /// 清空bucket
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel ClearBucket()
        {
            var res = TecentCosService.Instance().ClearBucket();
            return Success(res);
        }

        [HttpPost]
        public ResponseModel PutTest(dynamic obj)
        {
            byte[] byte1 = Convert.FromBase64String(obj.filedata.ToString());
            var watermarkRes = TecentCosService.Instance().PutObject("123.jpg", byte1);
            return base.Success(watermarkRes);
        }

        [HttpGet]
        public ResponseModel Test(string model)
        {
            AddWaterMark waterMark = JsonConvert.DeserializeObject<AddWaterMark>(model);
            return base.Success(waterMark);
        }

        [HttpPost]
        public FileStreamResult FileUpload()
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                var file = files[0];

                var fileResult = new FileStreamResult(file.InputStream, file.ContentType, file.FileName);
                return fileResult;
            }
            return null;
        }
        public class HAHA
        {
            public AA aa { get; set; }
            public string bb { get; set; }
        }
        public enum AA
        {
            a = 0,
            b = 1
        }
    }
}
